package com.xxl.sso.sample.config;

import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.filter.XxlSsoWebFilter;
import com.xxl.sso.core.util.JedisUtil;
import com.xxl.sso.sample.shiro.MyRealm;
import com.xxl.sso.sample.shiro.SsoFilter;
import com.xxl.sso.sample.shiro.XxlFilter;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.naming.NamingException;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 吕一明
 * @公众号 码客在线
 */
@Configuration
public class ShiroConfig {


    @Bean
    XxlFilter xxlFilter() {
        return new XxlFilter();
    }

    @Bean
    public SecurityManager securityManager(MyRealm realm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);

        System.out.println("securityManager -----------> 初始化了");
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {

        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);

        filterFactoryBean.setLoginUrl("/login");
        filterFactoryBean.setUnauthorizedUrl("/unauth");

        Map<String, Filter> filters = new HashMap<>();
        filters.put("ssoFilter", new SsoFilter());
        filters.put("xxlFilter", xxlFilter());

        filterFactoryBean.setFilters(filters);

        Map<String, String> hashMap = new LinkedHashMap<>();
        hashMap.put("/login", "anon");
        hashMap.put("/js/**", "anon");
        hashMap.put("/css/**", "anon");

        hashMap.put("/admin/*", "xxlFilter,ssoFilter"); //需要登录权限
        hashMap.put("/json", "xxlFilter,ssoFilter"); //需要登录权限
        hashMap.put("/logout", "xxlFilter"); //需要登录权限

        hashMap.put("/**", "anon");

        filterFactoryBean.setFilterChainDefinitionMap(hashMap);
        return filterFactoryBean;
    }

}
